<template>
  <t-dialog
    v-model:visible="visible"
    :header="dialogTitle"
    width="500"
    :confirm-btn="{ loading }"
    @confirm="dialogConfirm"
    @close="dialogHide"
  >
    <t-space direction="vertical" style="width: 100%">
      <t-form ref="form" reset-type="initial" :data="formData" :rules="FORM_RULES" :label-width="60">
        <t-form-item :label="t('pages.patch.name')" name="title">
          <t-input v-model="formData.title" maxlength="32" show-limit-number />
        </t-form-item>
        <t-form-item :label="t('common.description')" name="description">
          <t-textarea
            v-model="formData.description"
            :autosize="{ minRows: 3, maxRows: 6 }"
            resize="none"
            maxlength="255"
            show-limit-number
          />
        </t-form-item>
        <t-form-item :label="t('pages.patch.link')" name="url">
          <t-input v-model="formData.url" maxlength="255" show-limit-number />
        </t-form-item>
        <t-form-item :label="t('pages.patch.img')" name="img">
          <common-upload :url="formData.img?.url" type="img" @confirm="onChooseEnd" @remove="onChooseDel" />
        </t-form-item>
      </t-form>
    </t-space>
  </t-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';

import CommonUpload from '@/components/common-upload/index.vue';
import { t } from '@/locales';

import { FORM_PATCH_LIST_DATA, FORM_RULES, PatchListFormItem } from '../constants';

const loading = ref(false);
const emits = defineEmits(['confirm']);

const dialogTitle = ref('');
const type = ref('add');
const visible = ref(false);
const form = ref(null);
const formData = ref({ ...FORM_PATCH_LIST_DATA });

const onChooseEnd = (type: 'img', { id, url }: Recordable) => {
  formData.value[type] = { id, url };
};
const onChooseDel = (type: 'img') => {
  formData.value[type] = null;
};

const dialogShow = (action: 'add' | 'edit', row?: PatchListFormItem) => {
  visible.value = true;
  type.value = action;
  if (action === 'edit') {
    formData.value = JSON.parse(JSON.stringify(row));
    dialogTitle.value = `${t('common.edit')}【${row.title}】`;
  } else {
    dialogTitle.value = t('common.add');
  }
};
const dialogHide = () => {
  loading.value = false;
  form.value.reset();

  visible.value = false;
};
const dialogConfirm = async () => {
  const valid = await form.value.validate();
  if (valid !== true) {
    return;
  }

  loading.value = true;
  const data = JSON.parse(JSON.stringify(formData.value));

  emits('confirm', type.value, data);
};

defineExpose({
  dialogShow,
  dialogHide,
});
</script>
